//
//  AlbumShare.swift
//  
//
//  Created by wuxianda on 2024/11/4.
//

import Foundation
import UIKit
import Photos

class ImageWritingContext<T> {
  var value: T

  init(_ value: T) {
    self.value = value
  }
}

class AlbumShare: NSObject, ShareProtocol {
    static var type: String = "album"
    
    static var title: String = "保存图片"
    
    static var icon: String? = "album.png"
    
    static var selectedIcon: String?
    
    var acceptObjectTypes: ShareObjectType = [.image]
    
    var isSelected: Bool = false
    
    
    required override init() {
    }
    

    func shareImage(shareObject: ShareImageObject, completion: Completion?)  {
        var pointer: UnsafeMutableRawPointer?
        
        if let completion = completion {
            pointer = Unmanaged.passRetained(ImageWritingContext(completion)).toOpaque()
        }
        
        PHPhotoLibrary.requestAuthorization { status in
            DispatchQueue.main.async {
                if status == .restricted || status == .denied {
                    Dialog.shared.confirm(dialogId: nil, title: "无访问权限",
                                          message: "请在手机的「设置-隐私-照片」选项中，允许蔚蓝访问你的相册",
                                          confirmButtonText: "去设置",
                                          cancelButtonText: "取消",
                                          interactive: false, completion: { _ in
                        UIApplication.shared.open(URL(string: UIApplication.openSettingsURLString)!)
                    })
                }
                else {
                    UIImageWriteToSavedPhotosAlbum(shareObject.image, self, #selector(self.save(image:didFinishSavingWithError:contextInfo:)), pointer)
                }
            }
        }
        
    }
    
    @objc func save(image: UIImage, didFinishSavingWithError: NSError?, contextInfo: UnsafeMutableRawPointer?) {
        var completion: Completion?

        if let contextInfo = contextInfo {
            let pointer = Unmanaged<ImageWritingContext<Completion>>.fromOpaque(contextInfo)
            completion = pointer.takeRetainedValue().value
        }

        if didFinishSavingWithError != nil {
            Toast.shared.toast(type: nil, message: "保存失败", interactive: true, duration: 100, completion: nil)
            completion?(false)
        } else {
            Toast.shared.toast(type: nil, message: "保存成功", interactive: true, duration: 100, completion: nil)
            completion?(true)
        }
    }
}
